    //
//  CustomFormController.m
//  MClient
//
//  Created by Wang Fei on 10-8-11.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "CustomFormController.h"
#import "MCFunction.h"
#import "MClientAppDelegate.h"
#import "MServerDAO.h"
#import "MCUIToolkit.h"
#import "MCControl.h"
#import "DateTimeSelectView.h"
#import "LookupSelectView.h"
#import "MCSwitch.h"
#import "WithFormButtonsBar.h"
#import "MCImageView.h"

@interface CustomFormController (Private)
- (Boolean) isFormVaild;
- (void) setDataBeforeCommit;
- (void) constructFormData; 
@end

@implementation CustomFormController
@synthesize formLayout;
@synthesize customId;
@synthesize initialValues;
@synthesize keyValue;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	
	self.title = [formLayout objectForKey:@"lbl"];
	[self leftBarButton:@"返回" withStyle:UIBarButtonItemStylePlain selector:@selector(selectCancelAction:)];
	formButtons = [formLayout objectForKey:@"btn"];
	// 图片下载并加载完成，返回图片尺寸信息
	imageSizeMap = [[NSMutableDictionary alloc] init];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(getImageSize:)
												 name:@"ImageSize" object:nil];
	buttonCol = 1;
	if ([formLayout objectForKey:@"csty"]) {
		if ([[formLayout objectForKey:@"csty"] objectForKey:@"button_col"]) {
			buttonCol =  [[[formLayout objectForKey:@"csty"] objectForKey:@"button_col"] intValue];
			if (buttonCol > 3) {
				buttonCol = 3;
			}
		}
	}
	withFormButtons = [MCUIToolkit getWithFormButtons:formButtons];
	int withFormButtonsBarHeight = [MCUIToolkit getWithFormButtonsBarHeight:withFormButtons buttonCol:buttonCol];
	if (withFormButtonsBarHeight != 0) {
		WithFormButtonsBar *withFormButtonsBar = [[WithFormButtonsBar alloc] initWithFrame:CGRectMake(0, 0, self.width, withFormButtonsBarHeight)];
		withFormButtonsBar.tag = -8888;
		[withFormButtonsBar addWithFormButtons:withFormButtons buttonCol:buttonCol delegate:self];
		self.tableview.tableFooterView = withFormButtonsBar;
		[withFormButtonsBar release];
	}
	// 生成表单按钮
	if ([formButtons count] == 1) {
		[self rightBarButton:[[formButtons objectAtIndex:0] objectForKey:@"lbl"]
				   withStyle:UIBarButtonItemStyleDone 
					selector:@selector(selectAction:)];
	}
	else if ([formButtons count] > 1) {
		[self rightBarButton:@"操作" 
				   withStyle:UIBarButtonItemStyleDone 
					selector:@selector(selectAction:)];
	} else {
		self.rightBarButtonItem = nil;
	}
	
	[self constructFormData];
	
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter05-01.html";
}

- (void)keyboardDidHidden:(NSNotification*)aNotification
{
	self.tableview.frame = CGRectMake(0, 0, self.width, self.height);
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
	[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
	[self keyboardDidHidden:nil];
	int withFormButtonsBarHeight = [MCUIToolkit getWithFormButtonsBarHeight:withFormButtons buttonCol:buttonCol];
	if (withFormButtonsBarHeight != 0) {
		WithFormButtonsBar *withFormButtonsBar = [[WithFormButtonsBar alloc] initWithFrame:CGRectMake(0, 0, self.width, withFormButtonsBarHeight)];
		withFormButtonsBar.tag = -8888;
		[withFormButtonsBar addWithFormButtons:withFormButtons buttonCol:buttonCol delegate:self];
		self.tableview.tableFooterView = withFormButtonsBar;
		[withFormButtonsBar release];
	}
}

- (void)dealloc {
	[formLayout release];
	[formData release];
	[customId release];
	[initialValues release];
	[keyValue release];
	[withFormButtons release];
	[imageSizeMap release];
	[[NSNotificationCenter defaultCenter] removeObserver:self 
													name:@"ImageSize" 
												  object:nil];	
    [super dealloc];
}

#pragma mark ---- UITableView方法 ----
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return [[formLayout objectForKey:@"stn"] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [[[[formLayout objectForKey:@"stn"] objectAtIndex:section] objectForKey:@"item"] count];
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return [[[formLayout objectForKey:@"section"] objectAtIndex:section] objectForKey:@"lbl"] ;
}
 

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([[[formLayout objectForKey:@"stn"] objectAtIndex:section] objectForKey:@"lbl"] == nil ||
		[@"" isEqualToString:[[[formLayout objectForKey:@"stn"] objectAtIndex:section] objectForKey:@"lbl"]]
		||[[formLayout objectForKey:@"stn"] count] <= 1) {
		return 0;
	}	
	return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSMutableDictionary *appItem = [[[[formLayout objectForKey:@"stn"] 
									  objectAtIndex:indexPath.section]
									 objectForKey:@"item"]
									objectAtIndex:indexPath.row];
	int  lableStyle = [[appItem objectForKey:@"lbls"] intValue];
	NSString* aTitle = [MCUIToolkit getFieldLabel:appItem];
	NSString* aValue = [MCUIToolkit getFieldTextValue:formData
											  appItem:appItem
										 selectOption:[formData objectForKey:@"so"]];
	if ([[appItem objectForKey:@"v"] boolValue] == NO) {
		return 0;
	}
	
	NSString *fieldType = [MCUIToolkit getFieldType:appItem];
	char cFieldType;
	strncpy(&cFieldType, [fieldType UTF8String], 1);
	if (cFieldType == '0') {
		return CGRectGetHeight(clientView.frame) / 3 + 10;
	}
	if (cFieldType == 'S' && [[appItem objectForKey:@"rdy"] boolValue]) {
		NSString *name = [MCUIToolkit getFieldName:appItem];
		NSMutableDictionary *fieldData = [[formData objectForKey:@"data"] objectForKey:name];
		NSMutableArray *fileInfos = [fieldData objectForKey:@"fi"];
		if (fileInfos == nil || [fileInfos count] < 1) 
			return [MCFunction cellHeight:lableStyle withTitle:aTitle withValue:aValue withAppItem:appItem];
		NSMutableDictionary *fileInfo = [fileInfos objectAtIndex:0];
		NSString *fileName = [[NSString stringWithFormat:@"indexPath_Seciton%d_Row%d_%@", indexPath.section,
							   indexPath.row, [fileInfo objectForKey:@"fname"]] retain];
		MCSize *size = [imageSizeMap objectForKey:fileName];
		if (size && size.height > 0) {
			if (lableStyle > 0) {
				if (size.width < 300.0) {
					return size.height+20;
				}else {
					return size.height/(size.width/300.0)+20;
				}
			}else {
				if (size.width < 230.0) {
					return size.height+20;
				}else {
					return size.height/(size.width/230.0)+20;
				}
			}
		}
	}
	return [MCFunction cellHeight:lableStyle withTitle:aTitle withValue:aValue withAppItem:appItem];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger) section {
	if ([[formLayout objectForKey:@"stn"] count] > 1) {
		UILabel *sectionHead = [[UILabel alloc] init];
		sectionHead.text = [[[formLayout objectForKey:@"stn"] objectAtIndex:section] objectForKey:@"lbl"];
		sectionHead.textAlignment = UITextAlignmentCenter;
		sectionHead.font = [UIFont boldSystemFontOfSize:20];
		sectionHead.textColor = [UIColor whiteColor];
		sectionHead.backgroundColor = [UIColor colorWithPatternImage:self.userDefaults.skin_bgSectionImg];
		return sectionHead;
	} else {
		return nil;
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	NSMutableDictionary *appItem = [[[[formLayout objectForKey:@"stn"] 
									  objectAtIndex:indexPath.section]
									 objectForKey:@"item"]
									objectAtIndex:indexPath.row];
	
	UITableViewCell *cell = [MCFunction createCellForCustomForm:tableView 
														appItem:appItem
													  indexPath:indexPath 
													   formView:self.clientView];
	if ([[appItem objectForKey:@"v"] boolValue] == NO) {
		cell.hidden = YES;
	}
	
	UILabel *labelField = (UILabel *)[cell.contentView viewWithTag:-1];
	labelField.text = [MCUIToolkit getFieldLabel:appItem];
	
	NSString *valueText = [MCUIToolkit getFieldTextValue:formData
												 appItem:appItem
											selectOption:[formData objectForKey:@"so"]];
	
	NSString *fieldType = [MCUIToolkit getFieldType:appItem];
	char cFieldType;
	strncpy(&cFieldType, [fieldType UTF8String], 1);
	
	if (cFieldType != 'B') {
		if (cFieldType == 'S' && [[appItem objectForKey:@"rdy"] boolValue]) {
			NSString *name = [MCUIToolkit getFieldName:appItem];
			NSMutableDictionary *fieldData = [[formData objectForKey:@"data"] objectForKey:name];
			NSString *df= [fieldData objectForKey:@"df"] == nil?@"":[fieldData objectForKey:@"df"];
			NSMutableArray *fileInfos = [fieldData objectForKey:@"fi"];
			if (fileInfos == nil || [fileInfos count] < 1) 
				return cell;
			NSMutableDictionary *fileInfo = [fileInfos objectAtIndex:0];
			NSString *fileName = [fileInfo objectForKey:@"fname"];
			if (fileName == nil || [fileName length] == 0)
				return cell;
			NSString *fileLocation = [fileInfo objectForKey:@"lcn"];
			
			NSMutableDictionary *fileAttribute = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
												  fileName,@"fileName",
												  fileLocation,@"fileLocation",
												  @"download",@"actionType",
												  df,@"dataFrom",
												  [NSString stringWithFormat:@"%d", indexPath.section], @"indexPath_section",
												  [NSString stringWithFormat:@"%d", indexPath.row], @"indexPath_row",
												  nil];
			MCImageView *valueField = (MCImageView *)[cell.contentView viewWithTag:-2];
			
			NSMutableDictionary *field = [MCUIToolkit getField:appItem];
			if([field objectForKey:@"imgw"] && [field objectForKey:@"imgh"]) {
				valueField.imgw = [[field objectForKey:@"imgw"] intValue];;
				valueField.imgh = [[field objectForKey:@"imgh"] intValue];
			}
			
			if (valueField.image == nil) {
				valueField.fileAttribute = fileAttribute;
				[fileAttribute release];
			}else {
				int lableStyle = [[appItem objectForKey:@"lbls"] intValue];
				if (lableStyle > 0) {
					if (valueField.image.size.width < 300) {
						valueField.frame = CGRectMake(10, lableStyle==1?40:10, valueField.image.size.width, 35);
					}
				}else {
					if (valueField.image.size.width < 230) {
						valueField.frame = CGRectMake(80, lableStyle==1?40:10, valueField.image.size.width, 35);
					}
				}
			}
			return cell;
		}		
		if (cFieldType == '0') {
			@try {
				UIWebView *webView = (UIWebView *)[cell.contentView viewWithTag:-2];
				[webView loadHTMLString:valueText baseURL:nil];
				return cell;
			}
			@catch (NSException * e) {
			}
		}
		MCControl* valueField = (MCControl *)[cell.contentView viewWithTag:-2];
		NSMutableDictionary *style = [appItem objectForKey:@"style"];
		if (style != nil) {
			float fontSize = 16.0;
			if ([style objectForKey:@"font_color"]) {
				valueField.textColor = [MCFunction hexColor:[NSString stringWithFormat:@"%@64", [style objectForKey:@"font_color"]]];
			}
			if ([style objectForKey:@"font_size"]) {
				fontSize = [[style objectForKey:@"font_size"] floatValue]/0.75;
				valueField.font = [UIFont boldSystemFontOfSize:fontSize];
			}
			if ([style objectForKey:@"font_style"]) {
				NSString *fontStyle = [style objectForKey:@"font_style"];
				if ([fontStyle isEqualToString:@"B"]) {
					valueField.font = [UIFont boldSystemFontOfSize:fontSize];
				}else if ([fontStyle isEqualToString:@"I"]) {
					valueField.font = [UIFont italicSystemFontOfSize:fontSize];
				}else {
					valueField.font = [UIFont boldSystemFontOfSize:fontSize];
				}
			}
		}
		if (cFieldType == 'H'||cFieldType == 'I'||cFieldType == 'K'||cFieldType == 'L') {
			NSArray *selectIcons = [valueText componentsSeparatedByString:@"::"];
			if ([selectIcons count] > 1) {
				for(UIImageView *imageView in [valueField subviews]){
					[imageView removeFromSuperview];
				}
				NSString *iconLabel = [selectIcons objectAtIndex:1];
				NSArray *icons = [iconLabel componentsSeparatedByString:@","];
				for (int j = 0; j < [icons count]; j++) {
					NSString *icon = [icons objectAtIndex:j];
					UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(32 * j, 0, 24, 24)];
					imageView.image = [MCFunction scaleAndRotateImage:[UIImage imageNamed:icon] width:24.0 height:24.0];
					imageView.backgroundColor = [UIColor clearColor];
					[valueField addSubview:imageView];
					[imageView release];
				}
				return cell;
			} 
		}
		
		if (valueField.style == MCControl_TextField) {
			[valueField.control addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
			((UITextField*)valueField.control).delegate = self;
		}
		valueField.text = valueText;
	} else {
		MCSwitch *valueField = (MCSwitch *)[cell.contentView viewWithTag:-2];
		[valueField addTarget:self action:@selector(switchValue:) forControlEvents:UIControlEventValueChanged];
		if ([valueText isEqualToString:@"☑"]) {
			valueField.on = YES;
		}else {
			valueField.on = NO;
		}
	}
	
	return cell;
}	

- (void)switchValue:(UIControl *)sender {
	MCSwitch *valueField = (MCSwitch *)sender;
	NSMutableDictionary *fieldData = [[formData objectForKey:@"data"] objectForKey:valueField.fieldName];
	[fieldData setObject:valueField.on?@"1":@"0" forKey:@"value"];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
	NSMutableDictionary *appItem = [[[[formLayout objectForKey:@"stn"] objectAtIndex:indexPath.section]objectForKey:@"item"]objectAtIndex:indexPath.row];
	
	NSString *fieldType = [MCUIToolkit getFieldType:appItem];
	char cFieldType;
	strncpy(&cFieldType, [fieldType UTF8String], 1);
	
	if (cFieldType != 'C' && cFieldType != 'D') {
		if ([DateTimeSelectView instance].isShown) {
			[[DateTimeSelectView instance] selectCancelAction];
		}
	}
	if (cFieldType != '3' && cFieldType != '4') {
		if ([LookupSelectView instance].isShown) {
			[[LookupSelectView instance] selectCancelAction];
		}
	}else {
		if (![@"3" isEqualToString:[appItem objectForKey:@"lpst"]]) {
			if ([LookupSelectView instance].isShown) {
				[[LookupSelectView instance] selectCancelAction];
			}
		}
	}
	[[self findFirstResponder] resignFirstResponder];
	
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	if (cFieldType == 'S' || cFieldType == 'J') {
		NSString *fieldName = [MCUIToolkit getFieldName:appItem];
		NSMutableDictionary *fieldData = [[formData objectForKey:@"data"] objectForKey:fieldName];
		self.dataFrom = [fieldData objectForKey:@"df"] == nil?@"":[fieldData objectForKey:@"df"];
		NSMutableArray *fileArray = [fieldData objectForKey:@"fi"];
		if (fileArray == nil) {
			fileArray = [NSMutableArray array];
			[fileArray addObject:[NSMutableDictionary dictionary]];
			[fieldData setObject:fileArray forKey:@"fi"];
		}
		if ([fileArray count] == 0) {
			[fileArray addObject:[NSMutableDictionary dictionary]];
		}
		self.fileAttach = [fileArray objectAtIndex:0];
		char cReadFlag = [cell.reuseIdentifier characterAtIndex:1];
		if (cReadFlag == 'T') {
			[self viewFileContent];
			return;
		}
		
		self.fileField = ((MCControl*)[cell.contentView viewWithTag:-2]).text;
		
		[self showActionSheetOfFile:[MCUIToolkit getField:appItem]];
		return;
	}
	
	[MCFunction selectDetailForEditFormByAppItem:self 
										withCell:cell
										 appItem:appItem
										  record:formData
									 isQueryForm:NO];
}

#pragma mark ---- 事件处理方法 ----
- (void)withFormButtonsAction:(id) sender {
	if ([DateTimeSelectView instance].isShown) {
		[[DateTimeSelectView instance] selectCancelAction];
	} 
	if ([LookupSelectView instance].isShown) {
		[[LookupSelectView instance] selectCancelAction];
	}
	[[self findFirstResponder] resignFirstResponder];
	NSMutableDictionary *button = [withFormButtons objectAtIndex:((UIButton *)sender).tag];
	if ([MCErrorManagement showAuthMessage:button]) {
		return;
	}
	bool pageCheck = NO;
	if ([button objectForKey:@"pck"] != nil) {
		pageCheck = [[button objectForKey:@"pck"]boolValue];
	}
	NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
	[self setDataBeforeCommit];
	if (pageCheck) {
		if ([self isFormVaild]) {
			NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
											   buttonId,@"buttonId",
											   @"edit_form",@"buttonType",
											   self.customId == nil?@"":self.customId,@"dataObjectName",
											   formData,@"formData", nil];
			
			if ([button objectForKey:@"cfmi"] != nil && ![[button objectForKey:@"cfmi"] isEqualToString:@""]){
				[MCFunction pushViewByUrl:[button objectForKey:@"url"]
							   parameters:parameters 
						   confirmMessage:[button objectForKey:@"cfmi"] 
						   naviController:self.navigationController];
			}else{
				[MCFunction pushViewByUrl:[button objectForKey:@"url"]
							   parameters:parameters
						   confirmMessage:nil 
						   naviController:self.navigationController];
			}
			[parameters release];
		}
	}else {
		NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
										   buttonId,@"buttonId",
										   @"edit_form",@"buttonType",
										   self.customId == nil?@"":self.customId,@"dataObjectName",
										   formData,@"formData", nil];
		
		if ([button objectForKey:@"cfmi"] != nil && ![[button objectForKey:@"cfmi"] isEqualToString:@""]){
			[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
						   parameters:parameters 
					   confirmMessage:[button objectForKey:@"cfmi"] 
					   naviController:self.navigationController];
		}else{
			[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
						   parameters:parameters
					   confirmMessage:nil 
					   naviController:self.navigationController];
		}
		[parameters release];
	}	
}

- (void) selectAction: (id) sender {
	if ([DateTimeSelectView instance].isShown) {
		[[DateTimeSelectView instance] selectCancelAction];
	} 
	if ([LookupSelectView instance].isShown) {
		[[LookupSelectView instance] selectCancelAction];
	}
	[[self findFirstResponder] resignFirstResponder];
	if ([formButtons count] == 1) {
		NSMutableDictionary *button = [formButtons objectAtIndex:0];
		if ([MCErrorManagement showAuthMessage:button]) {
			return;
		}
		NSMutableDictionary *url = [button objectForKey:@"url"];
		bool pageCheck = NO;
		if ([button objectForKey:@"pck"]) {
			pageCheck = [[button objectForKey:@"pck"]boolValue];
		}
		NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
		[self setDataBeforeCommit];
		if (pageCheck) {
			if ([self isFormVaild]) {
				NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
												   buttonId,@"buttonId",
												   @"edit_form",@"buttonType",
												   self.customId == nil?@"":self.customId,@"dataObjectName",
												   formData,@"formData", nil];
				
				if ([button objectForKey:@"cfmi"] != nil && ![[button objectForKey:@"cfmi"] isEqualToString:@""]){
					[MCFunction pushViewByUrl:url
								   parameters:parameters 
							   confirmMessage:[button objectForKey:@"cfmi"] 
							   naviController:self.navigationController];
				}else{
					[MCFunction pushViewByUrl:url
								   parameters:parameters
							   confirmMessage:nil 
							   naviController:self.navigationController];
				}
				[parameters release];
			}
		}else {
			NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
											   buttonId,@"buttonId",
											   @"edit_form",@"buttonType",
											   self.customId == nil?@"":self.customId,@"dataObjectName",
											   formData,@"formData", nil];
			
			if ([button objectForKey:@"cfmi"] != nil && ![[button objectForKey:@"cfmi"] isEqualToString:@""]){
				[MCFunction pushViewByUrl:url 
							   parameters:parameters 
						   confirmMessage:[button objectForKey:@"cfmi"] 
						   naviController:self.navigationController];
			}else{
				[MCFunction pushViewByUrl:url
							   parameters:parameters 
						   confirmMessage:nil 
						   naviController:self.navigationController];
			}
			[parameters release];
		}
		
		return;
	}
	
	//导航bar上面的操作按钮弹出菜单
	UIActionSheet *menu = [MCUIToolkit actionSheet:formButtons
										   withTag:2
									  withDelegate:self
										 withTitle:@"选择操作"];
	[menu showFromTabBar:(UITabBar *)[self.navigationController view]];
}

- (void) selectCancelAction: (id) sender {
	[self.navigationController popViewControllerAnimated:YES];
}


- (void)navigationBarButtonActionSheetEvent:(NSInteger)buttonIndex
{
	if (buttonIndex == [formButtons count]) {
		// 按下取消按钮
		return;
	}
	
	NSMutableDictionary *button = [formButtons objectAtIndex:buttonIndex];
	if ([MCErrorManagement showAuthMessage:button]) {
		return;
	}
	bool pageCheck = NO;
	if ([button objectForKey:@"pck"] != nil) {
		pageCheck = [[button objectForKey:@"pck"]boolValue];
	}
	NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
	[self setDataBeforeCommit];
	if (pageCheck) {
		if ([self isFormVaild]) {
			NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
											   buttonId,@"buttonId",
											   @"edit_form",@"buttonType",
											   self.customId == nil?@"":self.customId,@"dataObjectName",
											   formData,@"formData", nil];
			
			if ([button objectForKey:@"cfmi"] != nil && ![[button objectForKey:@"cfmi"] isEqualToString:@""]){
				[MCFunction pushViewByUrl:[button objectForKey:@"url"]
							   parameters:parameters 
						   confirmMessage:[button objectForKey:@"cfmi"] 
						   naviController:self.navigationController];
			}else{
				[MCFunction pushViewByUrl:[button objectForKey:@"url"]
							   parameters:parameters
						   confirmMessage:nil 
						   naviController:self.navigationController];
			}
			[parameters release];
		}
	}else {
		NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
										   buttonId,@"buttonId",
										   @"edit_form",@"buttonType",
										   self.customId == nil?@"":self.customId,@"dataObjectName",
										   formData,@"formData", nil];
		
		if ([button objectForKey:@"cfmi"] != nil && ![[button objectForKey:@"cfmi"] isEqualToString:@""]){
			[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
						   parameters:parameters 
					   confirmMessage:[button objectForKey:@"cfmi"] 
					   naviController:self.navigationController];
		}else{
			[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
						   parameters:parameters
					   confirmMessage:nil 
					   naviController:self.navigationController];
		}
		[parameters release];
	}
}

- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {	
	if (actionSheet.tag == 1) {
		[self selectFilePathActionSheetEvent:buttonIndex actionSheet:actionSheet];
	}
	
	if (actionSheet.tag == 2) {
		[self navigationBarButtonActionSheetEvent:buttonIndex];
	}
}

- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	if ([self.operateFlag isEqualToString:@"getUploadFileName"]) {
		[self getUploadFileNameSuccess:returnValue];
	} else if ([self.operateFlag isEqualToString:@"uploadFile"]) {
		[self uploadFileSuccess];
	}
	if ([self.operateFlag isEqualToString:@"downloadFile"]) {
		[self downloadFileSuccess];
	}
}


- (void) constructFormData {
	formData = [[NSMutableDictionary alloc] init];
	[formData setObject:self.customId forKey:@"dto"];
	[formData setObject:self.customId forKey:@"layout"];
	NSMutableDictionary *datas = [NSMutableDictionary dictionary];
	NSMutableArray *sections = [formLayout objectForKey:@"stn"];
	if (sections != nil) {
		for(int i = 0; i < [sections count]; i++){
			NSMutableDictionary *section = [sections objectAtIndex:i];
			NSMutableArray *appItems = [section objectForKey:@"item"];
			for(int j = 0; j < [appItems count]; j++) {
				NSMutableDictionary *appItem = [appItems objectAtIndex:j];
				
				NSString *name = [MCUIToolkit getFieldName:appItem];			
				NSString *fieldType = [MCUIToolkit getFieldType:appItem];
				
				NSMutableDictionary *fieldData = [appItem objectForKey:@"fd"];
				if (fieldData == nil) {
					fieldData = [[NSMutableDictionary alloc] init];
					[fieldData setObject:@"" forKey:@"value"];
				}
				[datas setObject:fieldData forKey:name];
				if (![fieldData objectForKey:@"lbl"] || [@"" isEqualToString:[fieldData objectForKey:@"lbl"]]) {
					if([fieldType isEqualToString: @"3"] || [fieldType isEqualToString: @"4"] || [fieldType isEqualToString: @"U"]){
						NSString *relationObject = [MCUIToolkit getRelationObject:appItem];
						if(relationObject != nil && ![relationObject isEqualToString:@""]
						  && nil != [fieldData objectForKey:@"value"] && ![@"" isEqualToString:[fieldData objectForKey:@"value"]]){
							id relReturnObject = [[MServerDAO sharedInstance] getFormData:relationObject layoutName:@"" key:[fieldData objectForKey:@"value"] isEditable:@"1"];
							if(relReturnObject){
								NSMutableDictionary *relObject = (NSMutableDictionary *)relReturnObject;
								if ([relObject objectForKey:@"desc"]) 
									[fieldData setObject:[relObject objectForKey:@"desc"] forKey:@"lbl"];
							}
						}
					}
				}
				
				// 置表单数据的强制赋值
				for (int l = 0; l < [self.initialValues count]; l++) {
					NSMutableDictionary *initialValue = [self.initialValues objectAtIndex:l];
					if ([[initialValue objectForKey:@"fld"] isEqualToString:name]) {
						[initialValue setObject:@"init"forKey:@"flag"];
						if([initialValue objectForKey:@"value"] == nil){
							break;
						}
						[fieldData setObject:[initialValue objectForKey: @"value"] forKey:@"value"];
						[datas setObject:fieldData forKey:name];
						if([fieldType isEqualToString: @"3"] || [fieldType isEqualToString: @"4"] || [fieldType isEqualToString: @"U"]){
							NSString *relationObject = [MCUIToolkit getRelationObject:appItem];
							NSMutableArray *lookupBackFills = [appItem objectForKey: @"lpbf"];
							if(relationObject != nil && ![relationObject isEqualToString:@""]
							   && nil != [fieldData objectForKey:@"value"] && ![@"" isEqualToString:[fieldData objectForKey:@"value"]]){
								if (![fieldData objectForKey:@"lbl"] || lookupBackFills != nil) {
									id relReturnObject = [[MServerDAO sharedInstance] getFormData:relationObject layoutName:@"" key:[fieldData objectForKey:@"value"] isEditable:@"1"];
									if(relReturnObject){
										NSMutableDictionary *relObject = (NSMutableDictionary *)relReturnObject;
										if (![fieldData objectForKey:@"lbl"])
											[fieldData setObject:[relObject objectForKey:@"desc"] == nil?@"":[relObject objectForKey:@"desc"] forKey:@"lbl"];
										NSMutableDictionary *relDatas = [NSMutableDictionary dictionary];
										if ([relObject objectForKey:@"data"]){ 
											relDatas = [relObject objectForKey:@"data"];
										}
										
										if (lookupBackFills != nil) {
											for(int k = 0; k<[lookupBackFills count]; k++){
												NSMutableDictionary *lookupBackFill = [lookupBackFills objectAtIndex:k];
												NSString *fieldName = [lookupBackFill objectForKey:@"bf"];
												NSMutableDictionary *fieldDataLookupBack = [relDatas objectForKey:fieldName];
												[self setLookupBackFillByFieldName: [lookupBackFill objectForKey:@"fld"] fieldDataLookupBack:fieldDataLookupBack];	
											}
										}
									}
								}
							}
						}			
						break;
					}
				}
				if ([[appItem objectForKey:@"v"] boolValue] == NO) {
					[appItems removeObjectAtIndex:j];
					j--;
					continue;
				}
			}
		}
	}	
	for(int k = 0; k < [self.initialValues count]; k++){
		NSMutableDictionary *initialValue = [initialValues objectAtIndex:k];
		if (![initialValue objectForKey:@"flag"]) {
			NSMutableDictionary *initialData = [[NSMutableDictionary alloc] init];
			[initialData setObject:[initialValue objectForKey:@"value"] == nil?@"":[initialValue objectForKey:@"value"] forKey:@"value"];
			[datas setObject:initialData forKey:[initialValue objectForKey:@"fld"]];
		}
	}
	[formData setObject:datas forKey:@"data"];
}

#pragma mark ---- 类内部处理方法 ----
- (Boolean) isFormVaild {
	NSString *requiredFields = @"";
	for (NSMutableDictionary *section in [self.formLayout objectForKey:@"stn"]) {
		for (NSMutableDictionary *appItem in [section objectForKey:@"item"]) {
			if ([[appItem objectForKey:@"rqd"] boolValue]) {
				
				NSString *name = [MCUIToolkit getFieldName:appItem];
				NSString *fieldType = [MCUIToolkit getFieldType:appItem];
				NSMutableDictionary *fieldData = [[formData objectForKey:@"data"] objectForKey:name];
				if ([fieldType isEqualToString:@"S"] || [fieldType isEqualToString:@"J"] || [fieldType isEqualToString:@"Y"]) {
					NSMutableArray *fileInfos = [fieldData objectForKey:@"fi"];
					if (fileInfos != nil && [fileInfos count] > 0) {
						NSMutableDictionary *fileInfo = [fileInfos objectAtIndex:0];
						if ([fileInfo objectForKey:@"fname"] == nil || [[fileInfo objectForKey:@"fname"] isEqualToString:@""]) {
							requiredFields = [[requiredFields stringByAppendingString:[MCUIToolkit getFieldLabel:appItem]] stringByAppendingString:@","];
						}
					}
				}else {
					if ([fieldData objectForKey:@"value"] == nil || [[fieldData objectForKey:@"value"] isEqualToString:@""]) {
						requiredFields = [[requiredFields stringByAppendingString:[MCUIToolkit getFieldLabel:appItem]] stringByAppendingString:@","];
					}
				}
			}
		}
	}
	if ([requiredFields length] > 0) {
		[self messageBox:@"输入提示" 
				 message:[NSString stringWithFormat:@"下列域必须输入:\n%@",[requiredFields substringToIndex:[requiredFields length]-1]]
				delegate:self
	   cancelButtonTitle:nil
	   otherButtonTitles:@"确定"];
		return NO;
	}
	return YES;
}

- (void) setLookupBackFillByFieldName: (NSString *)fieldName fieldDataLookupBack:(NSMutableDictionary *)fieldDataLookupBack{	
	NSMutableDictionary *datas = [formData objectForKey:@"data"];
	NSMutableArray *sections = [formLayout objectForKey:@"stn"];
	if (sections != nil) {
		for(int i = 0; i < [sections count]; i++){
			NSMutableDictionary *section = [sections objectAtIndex:i];
			NSMutableArray *appItems = [section objectForKey:@"item"];
			for(int j = 0; j < [appItems count]; j++){
				NSMutableDictionary *appItem = [appItems objectAtIndex:j];
				NSString *name = [MCUIToolkit getFieldName:appItem];			
				NSString *fieldType = [MCUIToolkit getFieldType:appItem];
				
				if ([fieldName isEqualToString:name]) {
					if (![fieldDataLookupBack objectForKey:@"lbl"] || [[fieldDataLookupBack objectForKey:@"lbl"] isEqualToString:@""]) {
						if([fieldType isEqualToString: @"3"] || [fieldType isEqualToString: @"4"] || [fieldType isEqualToString: @"U"]){
							NSString *relationObject = [MCUIToolkit getRelationObject:appItem];
							if(relationObject != nil && ![relationObject isEqualToString:@""]){
								id relReturnObject = [[MServerDAO sharedInstance] getFormData:relationObject layoutName:@"" key:[fieldDataLookupBack objectForKey:@"value"] isEditable:@"1"];
								if(relReturnObject){
									NSMutableDictionary *relObject = (NSMutableDictionary *)relReturnObject;
									[fieldDataLookupBack setObject:[relObject objectForKey:@"desc"] == nil?@"":[relObject objectForKey:@"desc"] forKey:@"lbl"];
								}
							}
						}
					}
					[datas setObject:fieldDataLookupBack forKey:name];
				}
			}
		}
	}
}

- (void)autoBackFill:(NSString *)fieldName fieldValue:(NSString *)value 
{
	NSMutableDictionary *fieldData = [[formData objectForKey:@"data"] objectForKey:fieldName];
	if (fieldData) {
		[fieldData setObject:value == nil?@"":value forKey:@"value"];
		[self.tableview reloadData];
	}
}

- (void) setDataBeforeCommit {
	for (NSMutableDictionary *section in [self.formLayout objectForKey:@"stn"]) {
		for (NSMutableDictionary *appItem in [section objectForKey:@"item"]) {
			NSString *name = [MCUIToolkit getFieldName:appItem];			
			NSString *fieldType = [MCUIToolkit getFieldType:appItem];
			
			NSMutableDictionary *fieldData = [[formData objectForKey:@"data"] objectForKey:name];
			if ([fieldType isEqualToString:@"Y"]) {
				NSMutableArray *fileInfos = [fieldData objectForKey:@"fi"];
				if (fileInfos != nil) {
					if ([fileInfos count] == 0) {
						[fieldData removeObjectForKey:@"fi"];
					}else {
						for(int i = 0; i < [fileInfos count]; i++){
							NSMutableDictionary *fileInfo = [fileInfos objectAtIndex:i];
							if ([fileInfo objectForKey:@"state"]) {
								NSString *fileState = [fileInfo objectForKey:@"state"];
								if ([fileState isEqualToString:@"add"]) {
									[fileInfo setObject:@"A" forKey:@"opt"];
									[fileInfo removeObjectForKey:@"state"];
								}else if ([fileState isEqualToString:@"normal"]) {
									[fileInfo removeObjectForKey:@"state"];
								}else if ([fileState isEqualToString:@"del"]) {
									[fileInfo setObject:@"" forKey:@"fname"];
									[fileInfo setObject:@"D" forKey:@"opt"];
									[fileInfo removeObjectForKey:@"state"];
								}else if ([fileState isEqualToString:@"addDel"]) {
									[fileInfos removeObjectAtIndex:i];
									i--;
								}
							}
						}
					}	
				}
			} else if ([fieldType isEqualToString:@"J"] || [fieldType isEqualToString:@"S"]) {
				NSMutableArray *fileInfos = [fieldData objectForKey:@"fi"];
				if (fileInfos != nil) {
					if ([fileInfos count] == 1) {
						if (![[fileInfos objectAtIndex:0] objectForKey:@"fname"] || ![[fileInfos objectAtIndex:0] objectForKey:@"lcn"]) {
							[fieldData removeObjectForKey:@"fi"];
						}	
					}
				}
			}
		}
	}
}

#pragma mark 键盘相关处理
- (void)textFieldDidEndEditing:(UITextField *)textField {
	MCTextField *valueField = (MCTextField*)textField;
	NSMutableDictionary *fieldData = [[formData objectForKey:@"data"] objectForKey:valueField.fieldName];
	[fieldData setObject:valueField.text == nil?@"":valueField.text forKey:@"value"];
}

#pragma mark ---处理接收到的消息---
//- (void) getImageSize:(id)anObject
- (void)getImageSize:(NSNotification *)notification
{
	MCSize* size = [notification object];
	
	[imageSizeMap setObject:size forKey:size.filename];
	[size release];
	[self.tableview reloadData];
}

@end
